//
//  CalendarController.swift
//  ios
//
//  Created by zhuxietong on 2017/2/28.
//  Copyright © 2017年 zhuxietong. All rights reserved.
//

import UIKit
import JTAppleCalendar
import Eelay


public class DateEvent{
    public var identify:String = ""
    public var description:String = ""
    public var date:Date?
    
    public var model:NSMutableDictionary?
    public init(date:Date,desc:String) {
        self.date = date
        self.identify = date["yyyyMMdd"]
        self.description = desc
    }
    public init(identify:String,desc:String) {
        self.identify = identify
        self.description = desc
    }
}


open class OneDayCalendar: GesSideController {

    
    public var DayCellType:EeCalendarDayCell.Type = EeCalendarDayCell.self
    public var CalendarHeaderType:EeCalendarHeaderView.Type = EeCalendarHeaderView.self
    
    open override var initTopStyle: EeTopStyle{
        let style:EeTopStyle = EeTopStyle.transparent_light
        //        style.navBarBgAlpha = 0

        //        style.navBarBgStyle = .color(.brown)
        //        style.titleTextAttributes = [NSAttributedStringKey.foregroundColor:UIColor.red]
        return style
    }
    public var displayView:EeDateEventsView = DatesDisplayView1()
    public var validSelectCheck:(Date)->Bool = {_ in return true}
    public var confirmDate:(NSMutableDictionary)->Void = {_ in}
    
    public var scrollToedDate:Date?
    
    public var cellBackView = UIView()
    public func addScrollBackView() {
        let options: NSKeyValueObservingOptions = [NSKeyValueObservingOptions.new, NSKeyValueObservingOptions.old]
        
        calendarView.insertSubview(cellBackView, at: 0)
        calendarView.addObserver(self, forKeyPath: "contentSize", options: options, context: nil)
    }
    
    open var contentHeight:CGFloat{
        get{
            return  Swidth + 50.0 + 100.0
        }
    }
    
    open func updateCellBackViewFrame(){
        calendarView.insertSubview(cellBackView, at: 0)
        cellBackView.frame = CGRect(x: -space.x, y: -space.y, width: calendarView.contentSize.width + space.x, height: calendarView.contentSize.height + space.y)
    }
    
    override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        if keyPath == "contentSize" {
            updateCellBackViewFrame()
        }
        
        
    }

    var __calendarView:JTACMonthView? = nil
    
    open lazy var calendarView: JTACMonthView = { [unowned self] in
        
        // FIXME: prevent Swift bug, lazy property initialized twice from `init(coder:)`
        // return existing webView if webView already added
        let views = self.jo_contentView.subviews.filter {$0 is JTACMonthView } as! [JTACMonthView]
        if let calendarV:JTACMonthView = __calendarView{
            return calendarV
        }
        
        let flow = UICollectionViewFlowLayout()
        flow.scrollDirection = .horizontal
        
        let cview = JTACMonthView(frame: .zero)
        __calendarView = cview
        return cview
        }()

    public var space:(x:CGFloat,y:CGFloat) = (TP.separatorHeight,TP.separatorHeight)

    open override func viewDidLoad() {
        self.side = .bottom(height: contentHeight)
        super.viewDidLoad()
        buildView()

        calendarView.calendarDelegate = self
        calendarView.calendarDataSource = self
        calendarView.scrollDirection = UICollectionView.ScrollDirection.horizontal
        gestureAble = false
        
        calendarView.register(DayCellType, forCellWithReuseIdentifier: "day")
        calendarView.register(CalendarHeaderType, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "header")
        calendarView.minimumLineSpacing = space.x/2.0
        calendarView.minimumInteritemSpacing = space.y/2.0

        calendarView.isPagingEnabled = true
        calendarView.showsHorizontalScrollIndicator = false
        weak var wself = self
        
        displayView.confirmDate = {
            date in
            wself?.confirmDate(date)
            wself?.dismiss(animated: true, completion: nil)
        }
        
        
//        calendarView.reloadData()
//        weak var ws = self
        calendarView.reloadData(withAnchor: nil) {
            wself?.addScrollBackView()
        }
        addScrollBackView()
    }
    
    open func buildView() {

        let canleBt = UIButton()
        let confirmBt = UIButton()
        
        let backView = UIView()
        jo_contentView.eelay = [
            [backView,[ee.T.L.B.R]],
            [canleBt,[ee.L.B],"50",[ee.R]],
            //            [confirmBt,[ee.R.B],"50",[ee.X,ee.L]],
            [calendarView,[ee.L.R],[canleBt,ee.T,ee.B],"\(Swidth+40)".+1000],
            [displayView,[ee.T,64],[ee.L.R],[calendarView,ee.T,ee.B]],
        ]
        confirmBt.ui.bfont(size: 17).buttonColor(hex:"#ddd").ncolor(hex: "#ca191d").ntitle(title: "确认".loc)
        canleBt.ui.bfont(size: 17).buttonColor(hex:"#ddd").ncolor(hex: "#777").ntitle(title: "取消".loc)
        
        canleBt.addTarget(self, action: #selector(canle), for: .touchUpInside)
        
        //        self.automaticallyAdjustsScrollViewInsets = false
        
        cellBackView.backgroundColor = UIColor(shex: "#ddd")
        calendarView.backgroundColor = UIColor(shex: "#fff")

        
        jo_contentView.backgroundColor = UIColor(shex: "#ca191d")
        self.navigationItem.leftBarButtonItem = nil
    }
    

    @objc open func canle() {
        self.dismiss(animated: true, completion: nil)
    }
    
    
    open func didSelect(date:Date) {
        displayView.events = [["value":date,"name":"出发时间".loc].mutable_dictionary]
        
    }
    
    open override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        let dates = DataNode.path(node: "values", mo.model, value: NSMutableArray())
        var events = [NSMutableDictionary]()
        var date_vs = [Date]()
        dates.listObj { (one:NSMutableDictionary) in
            events.append(one)
            guard let d = DataNode<Date>.path(node: "value", one)else{return}
            date_vs.append(d)
            
        }
        displayView.events = events
        displayView.placeHolderL.text = mo.model["title","选择时间".loc]
        calendarView.selectDates(date_vs)

        if date_vs.count > 0 {
            calendarView.scrollToHeaderForDate(date_vs[0])
//            calendarView.scrollToDate(date_vs[0], triggerScrollToDateDelegate: true, animateScroll: false, preferredScrollPosition: nil, completionHandler: nil)
            return
        }
        guard let to_date = self.scrollToedDate else {
            return
        }
        calendarView.scrollToHeaderForDate(to_date)
//         calendarView.scrollToDate(to_date, triggerScrollToDateDelegate: true, animateScroll: false, preferredScrollPosition: nil, completionHandler: nil)
        

        
    }

    open override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //----------------------- JTAppleCalendarViewDelegate,JTAppleCalendarViewDataSource
    
    
    open func calendar(_ calendar: JTACMonthView, cellForItemAt date: Date, cellState: CellState, indexPath: IndexPath) -> JTACDayCell {
        let myCustomCell = calendar.dequeueReusableCell(withReuseIdentifier: "day", for: indexPath) as! EeCalendarDayCell
        myCustomCell.isSelectedCell = cellState.isSelected
        myCustomCell.titleL.text = cellState.text
        if cellState.dateBelongsTo == .thisMonth {
            myCustomCell.titleL.textColor = UIColor(shex: "#ca191d")
        } else {
            myCustomCell.titleL.textColor = UIColor(shex: "#ca191d00")
        }
        if !validSelectCheck(date){
            myCustomCell.titleL.textColor = UIColor(shex:"#ccc")
        }
        return myCustomCell
    }
    
    
    
    open func calendar(_ calendar: JTACMonthView, willDisplay cell: JTACDayCell, forItemAt date: Date, cellState: CellState, indexPath: IndexPath) {
        let myCustomCell = cell as! EeCalendarDayCell
        myCustomCell.isSelectedCell = cellState.isSelected
        myCustomCell.titleL.text = cellState.text
        if cellState.dateBelongsTo == .thisMonth {
            myCustomCell.titleL.textColor = UIColor(shex: "#ca191d")
        } else {
            myCustomCell.titleL.textColor = UIColor(shex: "#ca191d00")
        }
        if !validSelectCheck(date){
            myCustomCell.titleL.textColor = UIColor(shex:"#ccc")
        }
    }
    
    
    open func calendarSizeForMonths(_ calendar: JTACMonthView?) -> MonthSize? {
        return MonthSize(defaultSize: 80, months: [80: [.feb, .apr]])
    }
    
    
    open func configureCalendar(_ calendar: JTACMonthView) -> ConfigurationParameters {
        let formatter = DateFormatter()
        let today = Date()
        let year_str = today["yyyy"]
        var today_strs = today["yyyy MM dd"].components(separatedBy: " ")
        today_strs.remove(at: 0)
        today_strs.insert("\(Int(year_str)!+1)", at: 0)
        
        formatter.dateFormat = "yyyy MM dd"
        
        //        let monthSize = MonthSize(defaultSize: 50, months: [75: [.feb, .apr]])
        
        
        let endDate = formatter.date(from: today_strs.joined(separator: " "))! // You can use date generated from a formatter
        let startDate = Date()                                // You can also use dates created from this function
        
        let parameters = ConfigurationParameters(
            startDate: startDate,  // This is manditory and must be supplied by you
            endDate: endDate,      // This is manditory and must be supplied by you
            numberOfRows: 6,                       // Default
            calendar: Calendar.current,            // Default
            generateInDates:  .forAllMonths,       // Default
            generateOutDates: .tillEndOfRow,      // Default
            firstDayOfWeek:   .monday,             // Default
            hasStrictBoundaries: true
        )
        
        return parameters
    }
    
    
    open func calendar(_ calendar: JTACMonthView, didDeselectDate date: Date, cell: JTACDayCell?, cellState: CellState) {
        guard let myCustomCell = cell as? EeCalendarDayCell else{return}
        
        myCustomCell.isSelectedCell = cellState.isSelected
    }
    
    open func calendar(_ calendar: JTACMonthView, didSelectDate date: Date, cell: JTACDayCell?, cellState: CellState) {
        if self.validSelectCheck(date)
        {
            guard let myCustomCell = cell as? EeCalendarDayCell else{return}
            myCustomCell.isSelectedCell = cellState.isSelected
            didSelect(date: date)
        }
        else{
            calendar.deselectDates(from: date, to: date, triggerSelectionDelegate: true)
        }
    }
    
    public func calendar(_ calendar: JTACMonthView, shouldSelectDate date: Date, cell: JTACDayCell?, cellState: CellState) -> Bool {
        if cellState.dateBelongsTo == .thisMonth {
            return true
        }
        return false
    }
    
    
    open func calendar(_ calendar: JTACMonthView, headerViewForDateRange range: (start: Date, end: Date), at indexPath: IndexPath) -> JTACMonthReusableView {
        let header = calendar.dequeueReusableJTAppleSupplementaryView(withReuseIdentifier: "header", for: indexPath)
        if let c_header = header as? EeCalendarHeaderView{
            c_header.titleL.text = range.start["YYYY年MM月".loc]
        }
        return header
    }
    

   
}


extension OneDayCalendar:JTACMonthViewDelegate,JTACMonthViewDataSource
{
  
    
//    func sizeOfDecorationView(indexPath: IndexPath) -> CGRect {
//        return [0,0,Swidth,50]
//    }
    
    
}
//extension OneDayCalendar1:JTAppleCalendarViewDelegate,JTAppleCalendarViewDataSource
//{
//    func calendar(_ calendar: JTAppleCalendarView, willResetCell cell: JTAppleDayCellView) {
//    }
//
//    func calendar(_ calendar: JTAppleCalendarView, willDisplayCell cell: JTAppleDayCellView, date: Date, cellState: CellState) {
//        let myCustomCell = cell as! DayCell
//        myCustomCell.isSelected = cellState.isSelected
//        myCustomCell.titleL.text = cellState.text
//        if cellState.dateBelongsTo == .thisMonth {
//            myCustomCell.titleL.textColor = UIColor(shex: "#ca191d")
//        } else {
//            myCustomCell.titleL.textColor = UIColor(shex: "#ca191d99")
//        }
//        if !validSelectCheck(date){
//            myCustomCell.titleL.textColor = UIColor(shex:"#ccc")
//        }
//
//    }
//    
//
//    func configureCalendar(_ calendar: JTAppleCalendarView) -> ConfigurationParameters {
//        let formatter = DateFormatter()
//
//        let today = Date()
//        let year_str = today["yyyy"]
//        var today_strs = today["yyyy MM dd"].components(separatedBy: " ")
//        today_strs.remove(at: 0)
//        today_strs.insert("\(Int(year_str)!+1)", at: 0)
//
//        formatter.dateFormat = "yyyy MM dd"
//
//
//        let endDate = formatter.date(from: today_strs.joined(separator: " "))! // You can use date generated from a formatter
//        let startDate = Date()                                // You can also use dates created from this function
//
//        let parameters = ConfigurationParameters(
//            startDate: startDate,  // This is manditory and must be supplied by you
//            endDate: endDate,      // This is manditory and must be supplied by you
//            numberOfRows: 6,                       // Default
//            calendar: Calendar.current,            // Default
//            generateInDates:  .forAllMonths,       // Default
//            generateOutDates: .tillEndOfGrid,      // Default
//            firstDayOfWeek:   .monday              // Default
//        )
//        return parameters
//    }
//
//
//    func calendar(_ calendar: JTAppleCalendarView, didDeselectDate date: Date, cell: JTAppleDayCellView?, cellState: CellState) {
//        guard let myCustomCell = cell as? DayCell else{return}
//        myCustomCell.isSelected = cellState.isSelected
//    }
//    
//    func calendar(_ calendar: JTAppleCalendarView, didSelectDate date: Date, cell: JTAppleDayCellView?, cellState: CellState) {
//        if self.validSelectCheck(date)
//        {
//            guard let myCustomCell = cell as? DayCell else{return}
//            myCustomCell.isSelected = cellState.isSelected
//            didSelect(date: date)
//        }
//        else{
//            calendar.deselectDates(from: date, to: date, triggerSelectionDelegate: true)
//        }
//
//    }
//
//
//
//    
//    func calendar(_ calendar: JTAppleCalendarView, sectionHeaderSizeFor range: (start: Date, end: Date), belongingTo month: Int) -> CGSize {
//        return [Swidth,80]
//    }
//
//    func calendar(_ calendar: JTAppleCalendarView, headerViewForDateRange range: (start: Date, end: Date), at indexPath: IndexPath) -> JTAppleCollectionReusableView {
//
//        guard let header1 = header as? HeaderView  else {
//            return
//        }
//        header1.titleL.text = range.start["YYYY年MM月"]
//        return header1
//    }
//
//    
//}

extension OneDayCalendar{
    open class EeCalendarHeaderView: JTACMonthReusableView {
        public let titleL = UILabel()
        public let selectView = UIView()
        
        public let weeksView = UIStackView()
        
        public override init(frame: CGRect) {
            super.init(frame: frame)
            addLayoutRules()
        }
        
        open func addLayoutRules() {
            eelay = [
                [selectView,[ee.T.L.B.R]],
                [weeksView,[ee.L.B.R],"28"],
                [titleL,[weeksView,ee.T,ee.B,-8],[ee.L.R,[10,-10]]],

            ]
            selectView.backgroundColor = UIColor(shex: "#ca191d")
            _ = titleL.ui.cl_fff.center.font20.text(hex: "#fffa")
            
            weeksView.axis = .horizontal
            weeksView.backgroundColor = UIColor(shex: "#0008")
            weeksView.distribution = .fillEqually
            let weeks = ["一","二","三","四","五","六","日"]
            let  ws = weeks.map { (str) -> UILabel in
                let  one = UILabel()
                one.ui.center.text(hex: "#eee8").bfont13.text("\(str)")
                return one
            }
            for oe in ws
            {
                weeksView.addArrangedSubview(oe)
            }
        }
        
        required public init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        
    }
}

extension OneDayCalendar{

    open class EeCalendarDayCell:JTACDayCell {
        
        public let titleL = UILabel()
        public let infoL = UILabel()
        public let selectView = UIView()
        
        
        public override init(frame: CGRect) {
            super.init(frame: frame)
            addLayoutRules()
        }
        
        open func addLayoutRules() {
            self.backgroundColor = UIColor(shex: "#fff")
            contentView.eelay = [
                [selectView,[ee.T.L.B.R,[-1,-1,1,1]]],
                [titleL,[ee.X.Y]],
            ]
            contentView.clipsToBounds = true
            
            selectView.backgroundColor = UIColor(shex: "#3335")
            _ = titleL.ui.cl_fff.center
        }
        
        required public init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        open var isSelectedCell = false{
            didSet{
                if isSelectedCell
                {
                    self.didSelect()
                }
                else{
                    self.disSelect()
                }
            }
            
        }
        
        
    
        
//        open override var isSelected:Bool{
//            set{
//                super.isSelected = newValue
//                if newValue{
//                    self.didSelect()
//                }
//                else{
//                    self.disSelect()
//                }
//
//            }
//            get{
//                return super.isSelected
//            }
//        }
        
        open func didSelect() {
            selectView.backgroundColor = UIColor(shex:"#ddd")
    //        selectView.alpha = 0.7
        }
        
        open func disSelect() {
            selectView.backgroundColor = UIColor(shex:"#fff")

    //        selectView.alpha = 0.0
        }
        
        
    }

}
